﻿using NP.BPMReportPlatform.Contract;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.ElectronicSign;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.Enterprise.Utils.Http;
using SqlSugar;
using System;
using System.Linq;
using System.Threading.Tasks;
using static NP.BPMReportPlatform.Contract.Dtos.ContractEnum;

namespace NP.BPMReportPlatform.RecurringJobs
{
    public class ContractUpdateSyncJob : BpmReportPlatformRecurringJob, IContractUpdateSyncJob
    {
        private readonly INPRestHttpHelper _nPRestHttp;
        private readonly SqlSugarClient _db, _dbPlatform;
        private readonly IESService _eSService;
        private readonly ContractStatusService _contractStatusService;

        public ContractUpdateSyncJob(ISqlSugarAppService sqlSugarAppService,
            INPRestHttpHelper httpClient, IESService eSService, ContractStatusService contractStatusService)
        {
            _nPRestHttp = httpClient;
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _eSService = eSService;
            _contractStatusService = contractStatusService;
        }

        /// <summary>
        /// 更新合同相关信息(离职了，状态更新)
        /// </summary>
        /// <returns></returns>
        public async Task SyncContractData()
        {
            var resignationDate = new DateTime(2000, 1, 1);
            var users = await _dbPlatform.Queryable<Users>().Where(t => t.Status == 0 && t.ResignationDate > resignationDate).Select(t => t.WorkNumber).ToListAsync();

            try
            {
                // 将离职人员的合同归档
                if (users != null && users.Count() > 0)
                {
                    var needUpdateUsers = _dbPlatform.Queryable<UserContractEntity>().Where(t => SqlFunc.ContainsArray(users, t.WorkNumber)
                    && t.ContractStatus != ContractStatusEnum.已解除.GetHashCode()).ToList();
                    if (needUpdateUsers != null && needUpdateUsers.Count() > 0)
                    {
                        needUpdateUsers.ForEach(t =>
                        {
                            t.ContractStatus = ContractStatusEnum.已解除.GetHashCode();
                            t.ContractStatusName = ContractStatusEnum.已解除.ToString();
                        });
                        _dbPlatform.Updateable(needUpdateUsers).UpdateColumns(t => new { t.ContractStatus, t.ContractStatusName }).ExecuteCommand();
                    }
                }
            }
            catch (Exception)
            {
            }

            try
            {
                // 签署中的合同 状态检查
                var needCheckContracts = _dbPlatform.Queryable<UserContractEntity>().Where(t => (t.ContractStatus == ContractStatusEnum.签署中.GetHashCode() || t.ContractStatus == ContractStatusEnum.作废中.GetHashCode())
                    && !string.IsNullOrEmpty(t.SignFlowId)).ToList();
                if (needCheckContracts != null && needCheckContracts.Count() > 0)
                {
                    needCheckContracts.ForEach(t =>
                    {
                        var status = _eSService.GetSignDetail(t.SignFlowId).Result;
                        if (status == "2")
                        {
                            _contractStatusService.UpdateContractStatus(t.ContractCode, ContractStatusEnum.履行中);
                        }
                    });
                }

                // 签署中的合同三方协议 状态检查
                var needCheckContractChanges = _dbPlatform.Queryable<UserContractTripartiteAgreementEntity>().Where(t => (t.ChangeStatus == ContractChangeStatusEnum.签署中.GetHashCode() || t.ChangeStatus == ContractChangeStatusEnum.作废中.GetHashCode())
                    && !string.IsNullOrEmpty(t.SignFlowId)).ToList();
                if (needCheckContractChanges != null && needCheckContractChanges.Count() > 0)
                {
                    needCheckContractChanges.ForEach(t =>
                    {
                        var status = _eSService.GetSignDetail(t.SignFlowId).Result;
                        if (status == "2")
                        {
                            _contractStatusService.UpdateChangeContractStatus(t.ChangeContractCode, ContractChangeStatusEnum.签署成功);
                        }
                    });
                }
            }
            catch (Exception)
            {
            }

            try
            {
                // 合同结束日期到了的，状态改成已终止
                // 未生效的合同 状态 改成 履行中
                var needUpdateUsers = _dbPlatform.Queryable<UserContractEntity>().Where(t => (t.ContractStatus == ContractStatusEnum.履行中.GetHashCode() || t.ContractStatus == ContractStatusEnum.未生效.GetHashCode())).ToList();
                if (needUpdateUsers != null && needUpdateUsers.Count() > 0)
                {
                    needUpdateUsers.ForEach(t =>
                    {
                        if (t.ContractEndDate < DateTime.Now)
                        {
                            _contractStatusService.UpdateContractStatus(t.ContractCode, ContractStatusEnum.已终止);
                        }

                        if (t.ContractStatus == ContractStatusEnum.未生效.GetHashCode() && t.ContractStartDate < DateTime.Now)
                        {
                            _contractStatusService.UpdateContractStatus(t.ContractCode, ContractStatusEnum.履行中);
                        }

                    });
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        /// <summary>
        /// 更新法人公司电子签信息
        /// </summary>
        /// <returns></returns>
        public async Task SyncEsignCorporate()
        {
            await _eSService.CheckAllCompany();
        }
    }
}
